<template>
  <div class="permission-list">
    <a-page-header
      title="权限管理"
      sub-title="管理系统中的权限，包括新增、编辑、删除等操作。"
    />
    <a-divider />
    <a-row :gutter="16">
      <a-col :span="24">
        <a-card>
          <template #title>
            <a-space>
              <span>权限列表</span>
              <a-button type="primary" @click="showAddModal" v-permission="'system:permission:add'">
                <template #icon><plus-outlined /></template>新增权限
              </a-button>
            </a-space>
          </template>
          <a-tree
            :tree-data="permissionTree"
            :defaultExpandAll="true"
            :showLine="{ showLeafIcon: false }"
            @select="onSelect"
            class="permission-tree"
          >
            <template #title="{ title, key, type }">
              <div class="tree-node-content">
                <span class="node-title">
                  <span v-if="type === 1" class="node-icon"><folder-outlined /></span>
                  <span v-else-if="type === 2" class="node-icon"><file-outlined /></span>
                  {{ title }}
                  <a-tag v-if="type === 1" color="blue" class="node-tag">菜单</a-tag>
                  <a-tag v-else-if="type === 2" color="green" class="node-tag">按钮</a-tag>
                </span>
                <a-space class="node-actions">
                  <a-button type="link" size="small" @click.stop="showEditModal(key)" v-permission="'system:permission:edit'">
                    <template #icon><edit-outlined /></template>
                  </a-button>
                  <a-button type="link" size="small" @click.stop="showAddChildModal(key)" v-permission="'system:permission:add'">
                    <template #icon><plus-outlined /></template>
                  </a-button>
                  <a-popconfirm
                    title="确定要删除这个权限吗？这将同时删除其所有子权限！"
                    @confirm="handleDelete(key)"
                    ok-text="确定"
                    cancel-text="取消"
                  >
                    <a-button type="link" size="small" danger @click.stop v-permission="'system:permission:delete'">
                      <template #icon><delete-outlined /></template>
                    </a-button>
                  </a-popconfirm>
                </a-space>
              </div>
            </template>
          </a-tree>
        </a-card>
      </a-col>
    </a-row>

    <!-- 新增/编辑权限弹窗 -->
    <a-modal
      :title="modalTitle"
      :visible="modalVisible"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :confirmLoading="modalLoading"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="权限名称" name="name">
          <a-input v-model:value="formState.name" placeholder="请输入权限名称" />
        </a-form-item>
        <a-form-item label="权限编码" name="code">
          <a-input v-model:value="formState.code" placeholder="请输入权限编码" :disabled="isEdit" />
        </a-form-item>
        <a-form-item label="权限类型" name="type">
          <a-select v-model:value="formState.type">
            <a-select-option :value="1">菜单</a-select-option>
            <a-select-option :value="2">按钮</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="父级权限" name="parentId" v-if="!isEditRoot">
          <a-tree-select
            v-model:value="formState.parentId"
            :tree-data="permissionTreeSelect"
            placeholder="请选择父级权限"
            :disabled="isAddChild"
            tree-default-expand-all
            :show-search="true"
            :filter-tree-node="filterTreeNode"
          />
        </a-form-item>
        <a-form-item label="菜单路径" name="path" v-if="formState.type === 1">
          <a-input v-model:value="formState.path" placeholder="请输入菜单路径" />
        </a-form-item>
        <a-form-item label="组件路径" name="component" v-if="formState.type === 1">
          <a-input v-model:value="formState.component" placeholder="请输入组件路径" />
        </a-form-item>
        <a-form-item label="权限标识" name="permission">
          <a-input v-model:value="formState.permission" placeholder="请输入权限标识，如：system:user:add" />
        </a-form-item>
        <a-form-item label="图标" name="icon" v-if="formState.type === 1">
          <a-input v-model:value="formState.icon" placeholder="请输入图标名称" />
        </a-form-item>
        <a-form-item label="排序" name="sort">
          <a-input-number v-model:value="formState.sort" :min="0" style="width: 100%" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, computed } from 'vue';
import { message, PageHeader } from 'ant-design-vue';
import { PlusOutlined, EditOutlined, DeleteOutlined, FolderOutlined, FileOutlined } from '@ant-design/icons-vue';
import axios from 'axios';
import { checkPermission, checkAndWarnPermission } from '@/utils/permission';

export default defineComponent({
  name: 'PermissionList',
  components: {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    FolderOutlined,
    FileOutlined,
    APageHeader: PageHeader,
  },
  setup() {
    const permissionList = ref([]);
    const permissionTree = ref([]);
    const selectedPermission = ref(null);

    // 获取权限列表
    const fetchPermissionList = () => {
      axios.get('/api/permission/list')
        .then(response => {
          if (response.data.code === 200) {
            permissionList.value = response.data.data;
          } else {
            message.error(response.data.message || '获取权限列表失败');
          }
        })
        .catch(error => {
          console.error('获取权限列表失败:', error);
          message.error('获取权限列表失败');
        });
    };

    // 获取权限树
    const fetchPermissionTree = () => {
      axios.get('/api/permission/tree')
        .then(response => {
          if (response.data.code === 200) {
            // 转换后端数据为树形组件所需格式
            permissionTree.value = convertToTreeData(response.data.data);
          } else {
            message.error(response.data.message || '获取权限树失败');
          }
        })
        .catch(error => {
          console.error('获取权限树失败:', error);
          message.error('获取权限树失败');
        });
    };
    
    // 将后端权限数据转换为树形组件所需格式
    const convertToTreeData = (data) => {
      return data.map(item => ({
        key: item.id,
        title: item.name,
        type: item.type,
        parentId: item.parentId,
        code: item.code,
        path: item.path,
        component: item.component,
        permission: item.permission,
        icon: item.icon,
        sort: item.sort,
        children: item.children ? convertToTreeData(item.children) : []
      }));
    };

    // 删除权限
    const handleDelete = (id) => {
      axios.delete(`/api/permission/${id}`)
        .then(response => {
          if (response.data.code === 200) {
            message.success('删除成功');
            fetchPermissionTree();
          } else {
            message.error(response.data.message || '删除失败');
          }
        })
        .catch(error => {
          console.error('删除失败:', error);
          message.error('删除失败');
        });
    };

    // 选择权限节点
    const onSelect = (selectedKeys, info) => {
      if (selectedKeys.length > 0) {
        selectedPermission.value = info.node;
      } else {
        selectedPermission.value = null;
      }
    };

    // 新增/编辑权限相关
    const modalVisible = ref(false);
    const modalLoading = ref(false);
    const modalTitle = ref('新增权限');
    const isEdit = ref(false);
    const isAddChild = ref(false);
    const isEditRoot = ref(false);
    const formRef = ref(null);
    const formState = reactive({
      name: '',
      code: '',
      type: 1,
      parentId: null,
      path: '',
      component: '',
      permission: '',
      icon: '',
      sort: 0,
    });

    const rules = {
      name: [
        { required: true, message: '请输入权限名称', trigger: 'blur' },
        { max: 50, message: '权限名称不能超过50个字符', trigger: 'blur' },
      ],
      code: [
        { required: true, message: '请输入权限编码', trigger: 'blur' },
        { max: 50, message: '权限编码不能超过50个字符', trigger: 'blur' },
      ],
      type: [
        { required: true, message: '请选择权限类型', trigger: 'change' },
      ],
    };

    // 权限树选择器数据
    const permissionTreeSelect = computed(() => {
      const convertToTreeSelect = (list) => {
        return list.map(item => ({
          id: item.key,
          value: item.key,
          title: item.title,
          pId: item.parentId,
          isLeaf: !item.children || item.children.length === 0,
          children: item.children ? convertToTreeSelect(item.children) : [],
        }));
      };
      return convertToTreeSelect(permissionTree.value);
    });

    // 树节点搜索过滤
    const filterTreeNode = (inputValue, treeNode) => {
      return treeNode.title.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0;
    };

    // 显示新增权限弹窗
    const showAddModal = () => {
      isEdit.value = false;
      isAddChild.value = false;
      isEditRoot.value = false;
      modalTitle.value = '新增权限';
      formState.name = '';
      formState.code = '';
      formState.type = 1;
      formState.parentId = null;
      formState.path = '';
      formState.component = '';
      formState.permission = '';
      formState.icon = '';
      formState.sort = 0;
      modalVisible.value = true;
    };

    // 显示新增子权限弹窗
    const showAddChildModal = (parentId) => {
      isEdit.value = false;
      isAddChild.value = true;
      isEditRoot.value = false;
      modalTitle.value = '新增子权限';
      formState.name = '';
      formState.code = '';
      formState.type = 1;
      formState.parentId = parentId;
      formState.path = '';
      formState.component = '';
      formState.permission = '';
      formState.icon = '';
      formState.sort = 0;
      modalVisible.value = true;
    };

    // 显示编辑权限弹窗
    const showEditModal = (id) => {
      isEdit.value = true;
      isAddChild.value = false;
      
      // 获取权限详情
      axios.get(`/api/permission/${id}`)
        .then(response => {
          if (response.data.code === 200) {
            const permission = response.data.data;
            formState.id = permission.id;
            formState.name = permission.name;
            formState.code = permission.code;
            formState.type = permission.type;
            formState.parentId = permission.parentId;
            formState.path = permission.path || '';
            formState.component = permission.component || '';
            formState.permission = permission.permission || '';
            formState.icon = permission.icon || '';
            formState.sort = permission.sort || 0;
            
            // 判断是否为根节点
            isEditRoot.value = !permission.parentId;
            
            modalTitle.value = '编辑权限';
            modalVisible.value = true;
          } else {
            message.error(response.data.message || '获取权限详情失败');
          }
        })
        .catch(error => {
          console.error('获取权限详情失败:', error);
          message.error('获取权限详情失败');
        });
    };

    // 处理弹窗确认
    const handleModalOk = () => {
      formRef.value.validate().then(() => {
        modalLoading.value = true;
        const apiUrl = isEdit.value ? `/api/permission/${formState.id}` : '/api/permission';
        const method = isEdit.value ? 'put' : 'post';
        
        axios[method](apiUrl, {
          name: formState.name,
          code: formState.code,
          type: formState.type,
          parentId: formState.parentId,
          path: formState.path,
          component: formState.component,
          permission: formState.permission,
          icon: formState.icon,
          sort: formState.sort,
        })
          .then(response => {
            if (response.data.code === 200) {
              message.success(`${isEdit.value ? '编辑' : '新增'}成功`);
              modalVisible.value = false;
              fetchPermissionTree();
            } else {
              message.error(response.data.message || `${isEdit.value ? '编辑' : '新增'}失败`);
            }
          })
          .catch(error => {
            console.error(`${isEdit.value ? '编辑' : '新增'}失败:`, error);
            message.error(`${isEdit.value ? '编辑' : '新增'}失败`);
          })
          .finally(() => {
            modalLoading.value = false;
          });
      }).catch(error => {
        console.log('验证失败:', error);
      });
    };

    // 处理弹窗取消
    const handleModalCancel = () => {
      modalVisible.value = false;
    };

    onMounted(() => {
      fetchPermissionTree();
    });

    return {
      permissionList,
      permissionTree,
      permissionTreeSelect,
      selectedPermission,
      onSelect,
      handleDelete,
      modalVisible,
      modalLoading,
      modalTitle,
      isEdit,
      isAddChild,
      isEditRoot,
      formRef,
      formState,
      rules,
      showAddModal,
      showAddChildModal,
      showEditModal,
      handleModalOk,
      handleModalCancel,
      filterTreeNode,
    };
  },
});
</script>

<style scoped>
.permission-list .ant-tree {
  background-color: transparent;
}

.permission-tree .tree-node-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 4px 0;
}

.permission-tree .node-title {
  display: flex;
  align-items: center;
}

.permission-tree .node-icon {
  margin-right: 8px;
}

.permission-tree .node-tag {
  margin-left: 8px;
}

.permission-tree .node-actions {
  margin-left: 16px;
  opacity: 0.7;
  transition: opacity 0.3s;
}

.permission-tree .tree-node-content:hover .node-actions {
  opacity: 1;
}
</style>